import React from "react";
import {Button, Form} from "@douyinfe/semi-ui";
import {UserControllerService, UserLoginRequest} from "../../../service";
import { Toast } from '@douyinfe/semi-ui';
import {useDispatch, useSelector} from "react-redux";
import {login} from "../../../stores/userReducer";
import {useCookies} from "react-cookie";
import {useNavigate} from "react-router-dom";
const UserLoginView:React.FC=()=>{
    const navigate=useNavigate()
    const [cookies, setCookie, removeCookie] = useCookies();
    const dispatch=useDispatch();
    const handleSubmit=async (values: UserLoginRequest)=>{
        const res = await UserControllerService.userLogin(values);
        if(!res.data){
            Toast.error("登录失败："+res.message);
            return;
        }
        const sessionIdRes=await UserControllerService.getSessionId()
        setCookie("CSESSIONID",sessionIdRes.data,{'path':'/'})
        dispatch(login(res.data));
        Toast.info(
            {content:"登陆成功"}
        );
        navigate("/");
    }




    return (
        <div style={{
            width: "100%",
            height: "90%",
        }}>
            <div style={{
                position: "absolute",
                left:0,
                right:0,
                margin: "auto",
                width: "fit-content",
                textAlign: "center"
            }}>
                <Form style={{ width: 400 }} onSubmit={values=>{handleSubmit(values)}}>
                    {({ formState, values, formApi }) => (
                        <>
                            <h1>登录</h1>
                            <Form.Input field='userAccount' label='账号' style={{ width: '100%' }} placeholder='输入你的账号'></Form.Input>
                            <Form.Input field='userPassword' mode={"password"} label='密码' style={{ width: '100%' }} placeholder='输入你的密码'></Form.Input>
                            {/*<Form.Checkbox field='agree' noLabel>I have read and agree to the terms of service</Form.Checkbox>*/}
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <p>
                                    <span>Or</span><Button theme='borderless' style={{ color: 'var(--semi-color-primary)', marginLeft: 10, cursor: 'pointer' }}><a href={"/user/register"}>注册</a></Button>
                                </p>
                                <Button htmlType='submit' type="tertiary">登录</Button>
                            </div>
                        </>
                    )}
                </Form>
            </div>

        </div>
    );
}
export default UserLoginView;
